package com.stm.bi.report;

import com.stm.bi.core.util.DateUtils;
import com.stm.bi.dto.query.RegionalSaleQry;
import com.stm.bi.model.Chart;
import com.stm.bi.model.DateRange;
import com.stm.framework.core.context.UserHolder;
import com.stm.framework.core.util.FileResourceLoader;
import com.stm.framework.core.util.StringUtil;
import com.stm.framework.dbcp.JdbcService;
import com.stm.framework.dto.Response;
import com.stm.saas.api.CalendarCycleRemoteService;
import com.stm.saas.api.ProductConfigRemoteService;
import com.stm.saas.dto.vo.ProductConfigVO;
import com.stm.saas.model.CalendarCycle;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.math.RoundingMode;

import static com.stm.bi.constant.IndexConstants.QTY_FIELD;
import static com.stm.bi.constant.PlanConstants.TYPE_MONTH;

/**
 * @author liuyx
 * @date 2025/2/17 18:02
 */
@Component
public class RegionalSaleRankChartQueryExe extends AbsChartQueryExe<RegionalSaleQry, Chart>{
    @Resource
    private JdbcService jdbcService;

    @Resource
    private CalendarCycleRemoteService calendarCycleRemoteService;

    @Resource
    private ProductConfigRemoteService productConfigRemoteService;

    @Override
    public Chart query(Long orgId, String orgNo, RegionalSaleQry query) {
        Chart chart = new Chart();

        CalendarCycle cyc = calendarCycleRemoteService.getByOrg().get();
        DateRange dateRange = DateUtils.getYearFirstAndEnd(LocalDate.now().toString(), cyc.getMonth());

        Response<ProductConfigVO> prodResp = productConfigRemoteService.selectByOrgId(UserHolder.getOrgId());
        String salesDefinition = "dealing";
        if(prodResp != null && prodResp.getData() != null) {
            salesDefinition = prodResp.getData().getSalesDefinition();
        }
        if("delivery".equals(salesDefinition)) {
            salesDefinition = "dealing";
        }

        String selectSql = FileResourceLoader.getResourceAsString("/sql/adsBaseProvinceSales.sql");
        List<Map> maps = jdbcService.selectList(selectSql, new Object[]{
                orgId,
                query.getDeptId(),
                TYPE_MONTH,
                salesDefinition,
                dateRange.getStartDate(),
                dateRange.getEndDate(),
                QTY_FIELD});

        if (maps.isEmpty()) {
            return chart;
        }
        Map<String, BigDecimal> provinceTotalQtyMap = maps.stream()
                .collect(Collectors.groupingBy(
                        m -> (String) m.get("province_name"),
                        Collectors.reducing(
                                BigDecimal.ZERO,
                                m -> (BigDecimal) m.get(QTY_FIELD),
                                BigDecimal::add
                        )
                ));
        // 按销量倒序排序
        provinceTotalQtyMap = provinceTotalQtyMap.entrySet().stream()
                .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                .limit(10)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));
        //总销量
        double totalQty = maps.stream().map(m -> (BigDecimal) m.get(QTY_FIELD)).filter(Objects::nonNull).mapToDouble(BigDecimal::doubleValue).sum();
        // 计算前十省份销量占比
        List<List<Object>> datas = new ArrayList<>();
        for (String key : provinceTotalQtyMap.keySet()) {
            String name  = key;
            if (StringUtil.isNotEmpty(key) && key.equals("-99")){
                name = "其他";
            }
            // 省份名称
            List<Object> data = new ArrayList<>();
            data.add(name);
            // 省份销量
            BigDecimal qty = provinceTotalQtyMap.get(key);
            data.add(qty);
            // 省份销量占比
            if (totalQty != 0.0) {
                data.add(BigDecimal.valueOf(100 * qty.doubleValue() / totalQty).setScale(2, RoundingMode.HALF_UP));
            } else {
                data.add(BigDecimal.ZERO);
            }
            datas.add(data);

        }
        List<String> items = chart.getItems();
        items.add("销量");
        items.add("销量占比");
        chart.setDatas(datas).setItems(items);
        return chart;
    }

    @Override
    public String getReportName() {
        return "全国销量排名";
    }
}
